import { UIManager } from "../manager/UIManager";
import GlobalData from "./GlobalData";
import ItemCollect from "./ItemCollect";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CollectUI extends cc.Component {
    public static instance: CollectUI = null;

    @property({ type: [cc.Node], tooltip: "按钮s" })
    private tags: cc.Node[] = [];

    @property({ type: cc.Sprite, tooltip: "进度条" })
    private progress: cc.Sprite = null;
    @property({ type: cc.Label, tooltip: "进度条文字" })
    private labProgress: cc.Label = null;

    @property({ type: cc.Node, tooltip: "" })
    private items: cc.Node = null;
    @property({ type: cc.Node, tooltip: "item" })
    private item: cc.Node = null;

    private selectIndex: number = 0;

    protected onLoad() {
        CollectUI.instance = this;

        this.createItem();
        this.changeTag();
    }

    private createItem() {
        for (let i = 0; i < GlobalData.collectConfigs.length; i++) {
            const config = GlobalData.getCollectConfigById(i + 1);
            const item = cc.instantiate(this.item);
            item.parent = this.items;
            item.active = true;
            item.getComponent(ItemCollect).setData(config);
        }
    }

    private changeTag() {
        this.tags.forEach((o, i) => {
            const children = o.children;
            children[0].active = !(this.selectIndex === i);
            children[1].active = this.selectIndex === i;
        });

        const data = { cur: 0, max: 0 };
        this.items.children.forEach((o, i) => {
            const comp = o.getComponent(ItemCollect);
            if (comp.config?.type === this.selectIndex) {
                if (comp.config.progress >= 1) {
                    data.cur++;
                }
                data.max++;
                o.active = true;
            } else {
                o.active = false;
            }
        });
        this.progress.fillRange = data.cur / data.max;
        this.labProgress.string = `进度: ${data.cur}/${data.max}`;
    }

    private onBtnsClicked(event: cc.Event, data: cc.Event.EventCustom) {
        const name = event.target.name;
        switch (name) {
            case "btnClose":
                {
                    UIManager.ins.close();
                }
                break;
            case "tag":
                {
                    for (let i = 0; i < this.tags.length; i++) {
                        const tag = this.tags[i];
                        if (tag === event.target) {
                            this.selectIndex = i;
                            this.changeTag();
                            break;
                        }
                    }
                }
                break;
        }
        // console.log("onReviveClicked()===>按钮:", name);
    }
}